<template>
  <div class="wordbook-management">
    <div class="page-header">
      <h2>词书管理</h2>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="handleAdd">创建词书</el-button>
        <el-button :icon="Refresh" @click="loadWordbooks">刷新</el-button>
      </div>
    </div>

    <!-- 词书列表 -->
    <el-row :gutter="20">
      <el-col
        :span="8"
        v-for="book in wordbooks"
        :key="book.id"
        style="margin-bottom: 20px"
      >
        <el-card class="wordbook-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="book-title">
                <el-icon :size="24"><Collection /></el-icon>
                <span>{{ book.name }}</span>
              </div>
              <el-dropdown @command="(cmd) => handleCommand(cmd, book)">
                <el-button text :icon="MoreFilled" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit" :icon="Edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          
          <div class="book-content">
            <p class="book-description">
              {{ book.description || '暂无描述' }}
            </p>
            <div class="book-stats">
              <div class="stat-item">
                <el-icon><Reading /></el-icon>
                <span>{{ book.wordCount || 0 }} 个单词</span>
              </div>
              <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>{{ book.userCount || 0 }} 人学习</span>
              </div>
            </div>
            <div class="book-time">
              创建时间：{{ formatDate(book.createdAt) }}
            </div>
          </div>
          
          <template #footer>
            <el-button type="primary" text @click="handleViewWords(book)">
              查看单词列表
            </el-button>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty
      v-if="!loading && wordbooks.length === 0"
      description="暂无词书数据"
      :image-size="200"
    />

    <!-- 加载中 -->
    <div v-loading="loading" v-if="loading" style="height: 400px" />

    <!-- 添加/编辑词书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="词书名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入词书名称" />
        </el-form-item>
        <el-form-item label="词书描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入词书描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看单词列表对话框 -->
    <el-dialog
      v-model="wordsDialogVisible"
      :title="`${currentBook?.name} - 单词列表`"
      width="800px"
    >
      <div style="margin-bottom: 16px">
        <el-button type="primary" :icon="Plus" size="small" @click="handleAddWordToBook">
          添加单词
        </el-button>
      </div>
      <el-table :data="bookWords" style="width: 100%" max-height="500">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="word" label="单词" width="150" />
        <el-table-column prop="phonetic" label="音标" width="150" />
        <el-table-column prop="meaning" label="释义" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleRemoveWord(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  Delete,
  Collection,
  Reading,
  User,
  MoreFilled
} from '@element-plus/icons-vue'
import { getWordbookList, getWordbookById, createWordbook, updateWordbook, deleteWordbook, getWordbookWords, removeWordFromWordbook } from '../api/wordbook'

// 数据
const wordbooks = ref([])
const bookWords = ref([])
const loading = ref(false)
const currentBook = ref(null)

// 对话框
const dialogVisible = ref(false)
const wordsDialogVisible = ref(false)
const dialogTitle = ref('创建词书')
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref()

// 表单数据
const formData = ref({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入词书名称', trigger: 'blur' }
  ]
}

onMounted(() => {
  loadWordbooks()
})

// 加载词书列表
const loadWordbooks = async () => {
  loading.value = true
  try {
    const response = await getWordbookList()
    
    if (response.code === 200) {
      wordbooks.value = response.data
    } else {
      ElMessage.error(response.message || '加载词书列表失败')
    }
  } catch (error) {
    console.error('加载词书列表失败：', error)
    ElMessage.error('加载词书列表失败')
  } finally {
    loading.value = false
  }
}

// 添加词书
const handleAdd = () => {
  dialogTitle.value = '创建词书'
  isEdit.value = false
  formData.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑词书
const handleEdit = (book) => {
  dialogTitle.value = '编辑词书'
  isEdit.value = true
  formData.value = {
    id: book.id,
    name: book.name,
    description: book.description
  }
  dialogVisible.value = true
}

// 删除词书
const handleDelete = (book) => {
  ElMessageBox.confirm(
    `确定要删除词书"${book.name}"吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteWordbook(book.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadWordbooks()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除词书失败：', error)
      ElMessage.error('删除失败')
    }
  })
}

// 查看单词列表
const handleViewWords = async (book) => {
  currentBook.value = book
  wordsDialogVisible.value = true
  
  try {
    const response = await getWordbookWords(book.id)
    if (response.code === 200) {
      bookWords.value = response.data
    } else {
      ElMessage.error(response.message || '加载单词列表失败')
      bookWords.value = []
    }
  } catch (error) {
    console.error('加载单词列表失败：', error)
    ElMessage.error('加载单词列表失败')
    bookWords.value = []
  }
}

// 添加单词到词书
const handleAddWordToBook = () => {
  ElMessage.info('添加单词到词书功能开发中')
}

// 从词书移除单词
const handleRemoveWord = (word) => {
  ElMessageBox.confirm(
    `确定要从词书中移除"${word.word}"吗？`,
    '移除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await removeWordFromWordbook(currentBook.value.id, word.id)
      if (response.code === 200) {
        ElMessage.success('移除成功')
        // 重新加载单词列表
        handleViewWords(currentBook.value)
      } else {
        ElMessage.error(response.message || '移除失败')
      }
    } catch (error) {
      console.error('移除单词失败：', error)
      ElMessage.error('移除单词失败')
    }
  })
}

// 下拉菜单命令
const handleCommand = (command, book) => {
  if (command === 'edit') {
    handleEdit(book)
  } else if (command === 'delete') {
    handleDelete(book)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let response
        if (isEdit.value) {
          // 更新词书
          response = await updateWordbook(formData.value.id, formData.value)
        } else {
          // 创建词书
          response = await createWordbook(formData.value)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadWordbooks()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}
</script>

<style scoped>
.wordbook-management {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.wordbook-card {
  height: 100%;
  transition: all 0.3s;
}

.wordbook-card:hover {
  transform: translateY(-4px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.book-content {
  min-height: 150px;
}

.book-description {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 16px;
  min-height: 48px;
}

.book-stats {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.book-time {
  color: #c0c4cc;
  font-size: 12px;
}
</style>

